from helpers.director.shortcut import ModelTable,TablePage,ModelFields,page_dc,director,RowFilter
from . models import ProdRecord,ProdModel
from helpers.func.parseExcel import ExcelFields

class ProdRecordPage(TablePage):
    def get_label(self):
        return '生产批次'
    
    def get_template(self, prefer=None):
        return 'jb_admin/table_new.html'
    
    class tableCls(ModelTable):
        model = ProdRecord
        exclude =[]
        pop_edit_fields = []
        button_edit = True
        
        def dict_head(self, head):
            width  ={
                'no':130,
                'model':200,
            }
            head['width'] = width.get(head['name'])
            return head
        
        def get_operations(self):
            ops = super().get_operations()
            ops.append(
                    {'label':'导入EXCEL',
                     'editor':'com-btn',
                      'click_express':ProdRecordExcelImport().get_front_action()
                      }                    
                )
            return ops          

class ProdRecordExcelImport(ExcelFields):
    class Meta:
        model = ProdRecord
        exclude = ['model']
    
    def get_head_context(self):
        ctx = super().get_head_context()
        ctx.update({
            'title':'导入excel字段对照'
        })
        return ctx
    
    def get_front_action(self,):
        """
        发送到前端执行的代码。
        `ctx.row.par_row_pk = scope.ps.vc.par_row.pk` 用于从前端环境提取变量信息，可以overwrite该行代码
        """
        self_director_name = self.get_director_name()

        return '''
        var ctx = named_ctx["%(director_name)s"]
        ex.uploadfile({accept:".xlsx, .xls, .csv"})
            .then((resp)=>{
               if(scope.ps.vc.par_row){
                  return ex.director("%(director_name)s").call("parse_excel_head",{url:resp[0],par_row:scope.ps.vc.par_row.pk})
               }else{
                  return ex.director("%(director_name)s").call("parse_excel_head",{url:resp[0]}) 
               } })
            .then((resp)=>{ 
                ex.each(ctx.heads,head=>{head.options=resp.options});
                ctx.row=resp.row;
                if(scope.ps.vc.par_row){
                   ctx.row.par_row_pk = scope.ps.vc.par_row.pk
                }
                return cfg.pop_vue_com('com-form-one',ctx,{title:'字段对照(左边为系统预设名，右边为当前excel首行字段名)'})
            }).then((resp)=>{
                scope.ps.search()
                cfg.pop_vue_com('com-excel-process-result',resp,{
area:['800px', '90%%'],
title:'导入结果'
})
               
            })
        '''%{'director_name':self_director_name}
        
    def save_form(self):
        """ 普通的报错逻辑 , 如果有 par_row_pk 字段的话，需要重写 save_form 的row数据"""
        url = self.kw.pop('meta__url')
        
        product_dict = {}
        for inst in ProdModel.objects.all():
            product_dict[inst.no] = inst.pk
        
        #out_list = []
        #model = self._meta.model
        error_msg =[]
        index = 1
        input_len = 0
        for row in self.parser_excel(url,self.kw):
            index +=1
            if row['main_part_code'] not in product_dict:
                error_msg.append('第%s行:商品基本信息中找不到品号:%s'%(index,row['main_part_code']))
            elif ProdRecord.objects.filter(no= row['no']).exists():
                error_msg.append('第%s行:重复的数据:'%index)
            else:
                row['model_id']= product_dict[row['main_part_code']]
                row['count'] = int(float(row['count']))
                ProdRecord.objects.create(**row)
                input_len += 1
                #out_list.append(model(**row))
        
        self.process_msg = {
            'import_length':input_len,
            'messages':error_msg
        }
  
    
    def get_row(self):
        return getattr(self,'process_msg',self.process_msg)    

class ProdRecordForm(ModelFields):
    class Meta:
        model = ProdRecord
        exclude = []
    
    def dict_head(self, head):
        if head['name'] =='model':
            head['editor'] = 'com-field-pop-table-select'
            head.update({
                'table_ctx':ProdModelPicker().get_head_context(),
                'required':True,
                'options':[],
                'width':'230px',
            })
        return head
    
    def get_head_context(self):
        ctx = super().get_head_context()
        ctx.update({
            'width':'650px',
            'height':'600px',
            'title':'创建生产批次'
        })
        return ctx

class ProdModelPicker(ModelTable):
    model = ProdModel
    exclude =[]
    selectable = False
    def dict_head(self, head):
        if head['name']=='no':
            head['editor'] = 'com-table-foreign-click-select'
        return head
    
    class filters(RowFilter):
        names=['no','name']
        icontains =['no','name']

director.update({
    'prodrecord':ProdRecordPage.tableCls,
    'prodrecord.edit':ProdRecordForm,
    'prodrecord.model.picker':ProdModelPicker,
    'prodrecord.excel.import':ProdRecordExcelImport,
})

page_dc.update({
    'prodrecord':ProdRecordPage
})